package de.tuhh.simsearch.model.persistence.contentmgmt.files;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import de.tuhh.simsearch.model.persistence.contentmgmt.entities.FileEntity;
import de.tuhh.simsearch.model.persistence.contentmgmt.files.interfaces.FileAccessInterface;

/**
 * FileAccess is used to store, remove and access files on the file system. FileAccess implements the
 * FileAccessInterface.
 * 
 * @author SimSearch 1
 * @see FileAccessInterface
 */
public class FileAccess implements FileAccessInterface {

  @SuppressWarnings("unused")
  @Override
  public InputStream getFile(FileEntity entity) throws IOException {

    File file = new File(entity.getPath() + entity.getFileName());

    FileInputStream fis = null;

    if (file.canRead()) {

      try {

        fis = new FileInputStream(file);
      } catch (IOException ioe) {

        if (fis != null) {
          fis.close();
        }
        fis = null;
      }
    }

    return fis;
  }

  @Override
  public boolean saveFile(InputStream fileStream, FileEntity entity) throws IOException {

    boolean returnvalue = true;

    String path = entity.getPath();
    File folder = new File(path);
    File file = new File(path + entity.getFileName());

    FileOutputStream fos = null;

    try {
      if (!folder.exists()) {
        folder.mkdirs();
      }

      file.createNewFile();
      fos = new FileOutputStream(file);

      int data = 0;

      while ((data = fileStream.read()) != -1) {
        fos.write(data);
      }
    } catch (IOException e) {

      e.printStackTrace();
      returnvalue = false;
    } finally {

      if (fos != null) {

        fos.close();
      }
    }

    return returnvalue;
  }

  @Override
  public boolean removeFile(FileEntity entity) {

    boolean success = false;

    String path = entity.getPath();
    String name = entity.getFileName();
    File folder = new File(path);
    File file = new File(path + name);

    if (folder.exists()) {
      success = file.delete();
    }
    return success;
  }
}
